<script setup>
import { ref, defineProps, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useWebSocket } from '@vueuse/core'
import { useUserStore } from "@/store/user";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteChatApi } from "@/apis/chat";


const props = defineProps({
  selectedChatObject: {
    type: Object,
  },
  messageList: {
    type: Array,
  },
  addMessage: {
    type: Function,
  },
  deleteMessage: {
    type: Function,
  },
  getChatList: {
    type: Function,
  }
})

const userStore = useUserStore()

const route = useRoute()
const router = useRouter()

/* 输入框的内容 */
const messageText = ref('');

/* 聊天框的ref */
const message = ref(null);

/* 消息列表 */
// const messageList = ref();




// #region 格式化时间
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// #endregion


// #region websocket代码

// 创建 WebSocket 连接
// const { send, status, data, open, close } = useWebSocket('ws://localhost:8080/chat/' + props.selectedChatObject.id);
const { send, status, data, open, close } = useWebSocket('ws://8.134.78.60:8080/chat/' + userStore.userInfo.id);

// 存储接收到的消息
// const receivedMessages = ref([]);

// 监听 WebSocket 消息
watch(data, (newData) => {
  console.log(newData);

  // console.log(newData.indexOf(','));


  /* 判断是否被拉黑了，是否通信没连接，自己是否拉黑了对方 */
  if (newData.slice(0, newData.indexOf(',')) === 'LAHEI') {
    const lastCommaIndex = newData.lastIndexOf(','); // 最后一个逗号的索引
    const secondCommaIndex = newData.lastIndexOf(',', lastCommaIndex - 1); // 倒数第二个逗号的索引
    const message = newData.slice(secondCommaIndex + 1, lastCommaIndex); // 截取消息内容
    ElMessage.error(message)
    props.deleteMessage()
  }

  if (newData) {
    if (newData.slice(0, newData.lastIndexOf(',')) === 'ERROR') {
      ElMessage.error('发言不合规，请文明发言')
      /* 让父组件删除这条消息 */
      props.deleteMessage()
    } else {
      const lastCommaIndex = newData.lastIndexOf(','); // 最后一个逗号的索引
      const secondCommaIndex = newData.lastIndexOf(',', lastCommaIndex - 1); // 倒数第二个逗号的索引
      const message = newData.slice(0, secondCommaIndex); // 截取消息内容
      const sendId = parseInt(newData.slice(secondCommaIndex + 1)); // 截取发送者id


      receiveMessage(message, sendId)
    }
  }
});



/* 发送消息 */
function sendMessage() {
  if (messageText.value.trim()) {

    props.addMessage({
      sendId: userStore.userInfo.id,
      receiveId: props.selectedChatObject.receiveId,
      text: messageText.value,
      time: formatDate(new Date())
    })
    /* 发送消息  */
    send(messageText.value.trim() + "u" + props.selectedChatObject.receiveId);

    messageText.value = '';

    nextTick(() => {
      smoothScrollToBottom()
    });
  }
}


/* 接收消息 */
function receiveMessage(data, sendId) {
  /* sendId 是发送者的id, props.selectedChatObject.receiveId是当前聊天者的id。这两个一样才接收*/

  if (data, sendId === props.selectedChatObject.receiveId) {
    props.addMessage({
      sendId: props.selectedChatObject.receiveId,
      receiveId: props.selectedChatObject.sendId,
      text: data,
      time: formatDate(new Date())
    });


    /* 要提醒用户有新消息 */
    // set(userStore.unreadMessageCount, userStore.unreadMessageCount + 1)
  }


  nextTick(() => {
    smoothScrollToBottom()
  });
}



// #region 拉黑代码
const handleLaHei = async () => {
  // 确定是否要拉黑
  ElMessageBox.confirm('确定要拉黑该用户吗？您将删除与用户的连接和所有聊天记录，无法再接收该用户的消息。', '警告',).then(async () => {
    // 拉黑用户
    // 发送请求
    await deleteChatApi(userStore.userInfo.id, props.selectedChatObject.receiveId)
    //再次获得聊天列表
    await props.getChatList()
    ElMessage.success('拉黑成功')

    router.push('/message/chat/undefined') // 跳转到聊天列表页面

  }).catch(() => {
    // 取消操作
    ElMessage.info('取消操作')
  });
}

// #endregion





// 在组件挂载后连接 WebSocket
onMounted(async () => {
  // console.log(props.messageList);  

  // 连接 WebSocket
  open()

  setTimeout(() => {
    smoothScrollToBottom();
  }, 100); // 延迟100ms

});



/* 切换路由重新获取数据 */
watch(route, () => {
  // getMessageList()
  open()

  setTimeout(() => {
    smoothScrollToBottom();
  }, 100); // 延迟100ms

})


// 在组件卸载前断开连接
onBeforeUnmount(() => {
  close()

});

// #endregion



// #region 跳转到底部
/* 丝滑滚动到消息列表底部，适用于聊天时 */
function smoothScrollToBottom() {

  if (message?.value !== null) {
    // 平滑滚动到消息容器的底部
    message?.value.scrollTo({
      top: message.value.scrollHeight, // 滚动到内容的底部
      behavior: 'smooth'                  // 设置平滑滚动
    });
  }

}

// #endregion




/* 判断route的路径来确定现在是不是选中了某个聊天对象 */
const isChat = computed(() => {
  const receiveId = route.path.split('/')[3]
  return receiveId === 'undefined'
})


</script>

<template>
  <!-- 聊天框 -->
  <div class="chat-window" v-if="!isChat">
    <h3 v-if="!isChat">
      <span @click="$router.push('/user/' + selectedChatObject.receiveId)">
        {{ selectedChatObject == null ? '' : selectedChatObject.receiveUserName }}
      </span>


      <svg-icon @click="handleLaHei" class="icon" name="lahei"></svg-icon>
      <!-- <svg-icon class="icon" name="jubao"></svg-icon> -->

    </h3>

    <div class="messages" ref="message">
      <div v-for="(message, index) in messageList" :key="index"
        :class="{ 'sent': message.sendId === userStore.userInfo.id, 'received': message.sendId !== userStore.userInfo.id }">

        <!-- 消息内容 -->
        <p class="time">{{ message.time }}</p>
        <div v-if="message.sendId === selectedChatObject.sendId" class="text-avatar">
          <span class="text">{{ message.text }}</span>
          <img :src="selectedChatObject.sendAvatar || 'https://via.placeholder.com/40'" class="avatar" />
        </div>

        <div class="text-avatar" v-else>
          <img :src="selectedChatObject.receiveAvatar || 'https://via.placeholder.com/40'" class="avatar" />
          <span class="text">{{ message.text }}</span>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="input-area">
      <input type="text" v-model="messageText" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
  <div v-else style="display: flex; align-items: center; margin: 0 auto;">
    <el-empty description="点击左边的用户头像来聊天吧！" image-size="300px">
      <!-- :image="require('../assets/noinformation.svg')" -->
    </el-empty>
  </div>
</template>

<style lang='scss' scoped>
/* 拉黑与举报图标 */
.icon {
  margin-left: 20px;

}

//电脑端样式
@media screen and (min-width: 768px) {
  .chat-window {


    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .chat-window h3 {
    margin: 0;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    background-color: #f5f5f5;

    & span:hover {
      cursor: pointer;
      color: $highlight-color;
    }
  }

  .messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    max-height: 100000px;
  }

  .messages .received {
    padding-top: 50px;
    border-radius: 5px;
    width: 90%;

    .time {
      text-align: center;
      margin-bottom: 20px;
      color: #999;
    }

    .text-avatar {
      display: flex;
      align-items: center;
      justify-content: start;

      .text {
        background: #d9edf7;
        padding: 10px;
        border-radius: 5px;
      }

      .avatar {
        margin-right: 10px;
        border-radius: 50%;
        width: 40px;
        height: 40px;
      }
    }

  }

  .messages .sent {
    padding-top: 50px;
    border-radius: 5px;
    width: 100%;

    .time {
      text-align: center;
      margin-bottom: 20px;
      color: #999;
    }

    .text-avatar {
      display: flex;
      align-items: center;
      justify-content: end;

      .text {
        background: #d9edf7;
        padding: 10px;
        border-radius: 5px;
      }

      .avatar {
        width: 40px;
        height: 40px;
        margin-left: 10px;
        border-radius: 50%;
      }
    }


  }

  .input-area {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
    background-color: #f9f9f9;
    // width: 52vw;
    // border: 1px solid red;
  }

  .input-area input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }

  .input-area button {
    padding: 10px;
    margin-left: 5px;
    border: none;
    background-color: rgb(64, 158, 255);
    color: white;
    border-radius: 5px;
    cursor: pointer;
  }

}

//移动端样式
@media screen and (max-width: 768px) {
  .chat-window {

    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .chat-window h3 {
    margin: 0;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    background-color: #f5f5f5;

    & span:hover {
      color: $highlight-color;
    }
  }

  .messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    max-height: 100000px;

  }

  .messages .received {
    padding-top: 50px;
    border-radius: 5px;
    width: 90%;

    .time {
      text-align: center;
      margin-bottom: 20px;
      color: #999;
    }

    .text-avatar {
      display: flex;
      align-items: center;
      justify-content: start;

      .text {
        background: #d9edf7;
        padding: 10px;
        border-radius: 5px;
      }

      .avatar {
        margin-right: 10px;
        border-radius: 50%;
        width: 40px;
        height: 40px;
      }
    }

  }

  .messages .sent {
    padding-top: 50px;
    border-radius: 5px;
    width: 100%;

    .time {
      text-align: center;
      margin-bottom: 20px;
      color: #999;
    }

    .text-avatar {
      display: flex;
      align-items: center;
      justify-content: end;

      .text {
        background: #d9edf7;
        padding: 10px;
        border-radius: 5px;
      }

      .avatar {
        width: 40px;
        height: 40px;
        margin-left: 10px;
        border-radius: 50%;
      }
    }


  }

  .input-area {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
    background-color: #f9f9f9;
    // width: 52vw;
    // border: 1px solid red;
  }

  .input-area input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }

  .input-area button {
    padding: 10px;
    margin-left: 5px;
    border: none;
    background-color: rgb(64, 158, 255);
    color: white;
    border-radius: 5px;
    cursor: pointer;
  }

}
</style>